package lch.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lch.constant.RedisConstant;
import lch.dao.CheckGroupDao;
import lch.dao.SetmealDao;
import lch.entity.PageResult;
import lch.entity.QueryPageBean;
import lch.pojo.CheckGroup;
import lch.pojo.Setmeal;
import lch.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lch
 * @date 2019-12-22 17:02
 */
@Transactional
@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        System.out.println(setmeal + "," + setmeal.getAge());
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        this.setSetmealAndCheckGroup(setmealId, checkgroupIds);
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
        generateMobileStaticHtml();
    }

    //生成静态页面的方法
    public void generateMobileStaticHtml() {
        List<Setmeal> setmealList = setmealDao.findAll();
        generateMobileSetmealListHtml(setmealList);
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成的套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("setmealList", setmealList);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成的套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("setmeal", setmealDao.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer writer = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //输出在配置文件路径+/+文件名
            writer = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            template.process(map, writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        List<Map<String, Object>> list = setmealDao.findSetmealCount();
        return list;
    }

    @Override
    public Map<Object, Object> findSetmealById(Integer id) {
        Map<Object, Object> map = new HashMap<>();
        //查询套餐基本信息
        Setmeal setmeal = setmealDao.findById(id);
        map.put("setmeal", setmeal);
        //查询检查组
        List<CheckGroup> checkGroupList = checkGroupDao.findAll();
        map.put("checkGroupList", checkGroupList);
        //查询对应检查组id
        List<Integer> checkgroupIds = setmealDao.findCheckgroupIdsBySetmealId(id);

        map.put("checkgroupchoose", checkgroupIds);


        return map;
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //修改套餐基本信息
        setmealDao.edit(setmeal);
        //清理中间表
        Integer id = setmeal.getId();
        setmealDao.deleteAssocication(id);
        //重新建立关系
        this.setSetmealAndCheckGroup(id,checkgroupIds);
    }


    public void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {

        for (Integer checkgroupId : checkgroupIds) {
            HashMap<String, Integer> map = new HashMap<>();
            map.put("checkgroup_id", checkgroupId);
            map.put("setmeal_id", setmealId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }
}
